#include <stdio.h>

#include "core.h"
#include "screen.h"
#include "input.h"
#include "audio.h"
#include "exception.h"
#include "menu.h"
#include "bbox.h"
#include "game.h"


int main(int argc, char **argv)
{
  menu *Menu;
  game *Game;

  try
  {
    core::init();
    if(audio::init()) printf("Error: Couldn't set up audio!\n");
    audio::openMusic("cyborgjeff-mamour1.it");
    audio::playMusic();

    screen::setTextColor(rgb_t(0, 255, 0));
    screen::setTextAlign(screen::HA_CENTER|screen::VA_TOP);

    Menu = new menu();
    Game = new game();

    while(!input::isQuitRequested())
    {
      input::update();
      std::string buf = input::getTextBuffer();
      printf("%s", buf.c_str());
      input::clearTextBuffer();

      if(!Menu->hasSplashBeenShown())
		Menu->splashScreen();
	  
	  v2<int> cursorPos;
	  bool clicked = input::getCursor(cursorPos);
	  
	  screen::drawSprite("ball", cursorPos.x, cursorPos.y);
	  
	  bbox cursor(cursorPos.x, cursorPos.y, cursorPos.x+1, cursorPos.y+1);
	  bbox cursorCollision;
	  bbox bboxSinglePlayer(0, 80, 240, 80+30);
	  bbox bboxMultiPlayer(240, 120, 240+240, 120+30);
	  bbox bboxQuit(240, 160, 240+240, 160+30);
	  
	  
	  
	  if((cursorCollision = bbox::intersection(cursor, bboxSinglePlayer)) > 0)
	  {
        Menu->drawMainMenu('s');
        if(clicked && !Game->running())
		  Game->startSinglePlayerVsAI();
	  }
	  
	  else if((cursorCollision = bbox::intersection(cursor, bboxMultiPlayer)) > 0)
	  {
		Menu->drawMainMenu('m'); 
		if(clicked)
		  puts("m"); 
	  }
	  
	  else if((cursorCollision = bbox::intersection(cursor, bboxQuit)) > 0)
	  {
		Menu->drawMainMenu('q');
		if(clicked)
		  core::quit(); // not sure how you'd like me to quit, but this causes a seg fault
	  }
	  
	  else
        Menu->drawMainMenu();
      //screen::drawSprite("ball", 64, 96);
      //screen::drawText("Hello, World!\nNew line", 240, 0);
      screen::update();
    }
  }
  catch(exception &e)
  {
    printf("Exception ocurred: %s\n", (const char*)e);
    printf("Terminating application.");
    core::quit();
    return 1;
  }

  core::quit();

  return 0;
}
